import { Context, h, Logger, Session } from 'koishi';

export const name = 'onion-middleware-demo';

// 一个简单的异步延迟函数
function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 前置中间件，先注册的优先级高
// 普通中间件，后注册的优先级高

export function apply(ctx: Context) {
  let ping_cnt = 0;

  // B. awa-awa!!
  ctx.middleware(async (session, next) => {
    const loggerB = new Logger(`B`);
    loggerB.info(`B`);
    await sleep(10); // 模拟耗时操作
    if (session.content.includes('awa')) {
      return `awa!!`;
    }
    const result = await next();
    return `result next of B: ${result}`;
  }, true);

  // A. 计时
  ctx.middleware(async (session, next) => {
    const loggerA = new Logger(`A`);
    loggerA.info(`A`);
    const start = Date.now();
    await sleep(10); // 模拟耗时操作
    const result = await next();
    const end = Date.now();
    loggerA.info(`消息处理结束，控制权流回上游。总耗时: ${end - start}ms`);
    return `result next of A: ${result}`;
  }, true);


  // C. qwq-qwq!!
  ctx.middleware(async (session, next) => {
    const loggerC = new Logger(`C`);
    loggerC.info(`C`);
    await sleep(10); // 模拟耗时操作
    if (session.content.includes('qwq')) {
      return `qwq!!`;
    }
    const result = await next();
    return `result next of C: ${result}`;
  });

  // D. ping-pong
  ctx.middleware(async (session, next) => {
    const loggerD = new Logger(`D`);
    loggerD.info(`D`);
    ping_cnt++;
    await sleep(10); // 模拟耗时操作
    if (session.content.includes('ping')) {
      return `pong`;
    }
    const result = await next();
    return `result next of D: ${result}`;
  });

  // E. ping-cnt
  ctx.command('ping-cnt', '测试连接')
    .action(async ( {session, options} ) => {
      const loggerE = new Logger(`E`);
      loggerE.info(`E`);
      await sleep(10); // 模拟耗时操作
      const response = `ping_cnt = ${ping_cnt}`;
      // return response;
      await session.send(response);
      return;
    });

  console.log('Koishi 洋葱模型插件示例已成功加载。');
  console.log('---------------------------------');
  console.log('请尝试发送以下消息以观察数据流：');
  console.log('1. 发送 "ping"');
  console.log('2. 发送 "你好"');
  console.log('3. 修改代码中的 blacklistedId 为你的用户ID，再发送 "ping"');
  console.log('---------------------------------');
}